package com.fingard.dsp.bank.directbank.vbao02;

import java.net.URLEncoder;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.vbao02.util.Base64ForRSA;
import com.fingard.dsp.bank.directbank.vbao02.util.RSAUtil;
import com.fingard.dsp.bank.directbank.vbao02.util.SignUtil;
import com.fingard.dsp.bank.directbank.vbao02.util.VbaoChargePostHandler;

public class VBAO02Base extends DirectBase{
	public String getCharset() {
		return getBankConfig().getCharset("UTF-8");
	}
	
	public String getSFTPDir(String p_reqPath) {
		if (p_reqPath.endsWith("/")) {
			return p_reqPath;
		} else {
			return p_reqPath + "/";
		}
	}
	
	/**
	 * 数据发送银行
	 * 
	 * @param reqData
	 * @param actItem
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public JSONObject sendToBank(String reqData, ActSetItem actItem, String url) throws Exception {
		// 1、MD5签名
		@SuppressWarnings("unchecked")
		Map<String, Object> mapSend = JSONObject.parseObject(reqData, Map.class);
        String signSend = SignUtil.getSignContent(mapSend);
        WriteBankLogLn2("微保签名原始数据:\r\n" + signSend);
        String sign = SignUtil.getDigest(signSend + actItem.saltKey);
        mapSend.put("sign", sign);
        
        reqData = JSONObject.toJSONString(mapSend);
        WriteBankLogLn2("发送微保请求数据明文:\r\n" + reqData);
        
        // 2、RSA公钥加密
        PublicKey publicKey = RSAUtil.getRSAPublicKeyByFileSuffix(actItem.oppCertFilePath, "pem", "RSA");
        byte[] encryBytes = RSAUtil.encrypt(reqData.getBytes(getCharset()), publicKey, 2048, 11, "RSA/ECB/PKCS1Padding");
        reqData = URLEncoder.encode(new String(Base64ForRSA.encode(encryBytes).getBytes(), getCharset()), getCharset());
        WriteBankLogLn2("发送微保请求数据密文:\r\n" + reqData);
        
        WriteBankUrlLogLn(url);
        
        VbaoChargePostHandler vbaoChargeHandler = new VbaoChargePostHandler();
		String tmpStrRet = vbaoChargeHandler.http(url, reqData, actItem.merchantId, bankFront.org);
        WriteBankLogLn2("微保响应数据密文:\r\n" + tmpStrRet);
        
		return JSONObject.parseObject(tmpStrRet);
	}
	
	/**
	 * RSA解密
	 * 
	 * @param p_reqJson
	 * @param actItem
	 * @return
	 * @throws Exception
	 */
	public JSONObject decryptByRSA(JSONObject p_reqJson, ActSetItem actItem) throws Exception {
		PrivateKey privateKey = RSAUtil.getRSAPrivateKeyByFileSuffix(actItem.ownKeyStorePath, "pem", null, "RSA");
        byte[] decodeBase64Bytes = Base64ForRSA.decode(p_reqJson.getString("reqmsg"));
        String decodeStr = new String(RSAUtil.decrypt(decodeBase64Bytes, privateKey, 2048, 11, "RSA/ECB/PKCS1Padding"),getCharset());
        WriteBankLogLn2("解密微保响应数据明文:\r\n" + decodeStr);
        
        return JSONObject.parseObject(decodeStr);
	}
}
